import { message, Space, Popconfirm, Tag, Card, Descriptions, Table } from "antd";
import { ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconUserAdd, IconRefresh, IconDownload, IconPlay, IconStop, IconReply, IconCopyAdd } from "@douyinfe/semi-icons";
import { useModel } from "umi";

import useHelperGateway from "../../helper/useHelperGateway";

import useCreateDatabaseUser from "../../hooks/gateway/useCreateDatabaseUser";
import useCreateDatabase from "../../hooks/gateway/useCreateDatabase";
import useAllServices from "../../hooks/gateway/useAllServices";
import useCreateDataService from "../../hooks/gateway/useCreateDataService";
import useUpdateServiceStatus from "../../hooks/gateway/useUpdateServiceStatus";
import useStopService from "../../hooks/gateway/useStopService";
import useDeleteService from "../../hooks/gateway/useDeleteService";
import useUpdateUsageStatus from "../../hooks/person/useUpdateUsageStatus";
import useInitialization from "../../hooks/person/useInitialization";
import useResetInitialization from "../../hooks/person/useResetInitialization";

const PersonDatabase = ({ reloadData }) => {
    const { selectedPerson } = useModel("gateway.info");
    const { openUpdateDatabaseStructureModal } = useHelperGateway();

    const { loading: createUserLoading, createDatabaseUser } = useCreateDatabaseUser();
    const { loading: createDBLoading, createDatabase } = useCreateDatabase();
    const { loading, services, loadAllServices } = useAllServices();
    const { loading: createDataServiceLoading, createDataService } = useCreateDataService();
    const { loading: updateStatusLoading, updateServiceStatus } = useUpdateServiceStatus();
    const { loading: stopLoading, stopService } = useStopService();
    const { loading: deleteLoading, deleteService } = useDeleteService();
    const { loading: usageLoading, updateUsageStatus } = useUpdateUsageStatus();
    const { loading: initLoading, personInitialization } = useInitialization();
    const { loading: resetLoading, resetInitialization } = useResetInitialization();

    const updatePersonStatus = () => {
        let usageStatus = !selectedPerson.usageStatus;
        let items = services.filter((item) => item.serviceRunning === true);
        if (usageStatus === true && items.length === 0) return message.error("没有正在运行的数据服务, 不能启用组织");
        if (usageStatus === false && items.length > 0) return message.error("有正在运行的数据服务, 不能停用组织");

        updateUsageStatus(usageStatus, (res) => {
            if (res) {
                message.success("成功更改可用状态");
                reloadData();
            }
        });
    };

    const updatePersonInit = () => {
        if (!selectedPerson.initializationStatus && !selectedPerson.usageStatus) return;
        selectedPerson.initializationStatus
            ? resetInitialization((res) => {
                  if (res) {
                      message.success("成功取消初始化");
                      reloadData();
                  }
              })
            : personInitialization((res) => {
                  if (res) {
                      message.success("成功初始化数据");
                  }
                  reloadData();
              });
    };

    let statusExtraActions = [];
    let extraActions = [];

    statusExtraActions.push(
        <Popconfirm
            key={1}
            title={`确认要在该网关${selectedPerson.usageStatus ? "停用" : "启用"}个人服务吗?`}
            placement="topRight"
            okButtonProps={{ loading: usageLoading }}
            onConfirm={updatePersonStatus}
        >
            <Button loading={usageLoading} type={selectedPerson.usageStatus ? "danger" : "primary"} icon={selectedPerson.usageStatus ? <IconStop /> : <IconPlay />}>
                {selectedPerson.usageStatus ? "停用" : "启用"}
            </Button>
        </Popconfirm>
    );

    if (!selectedPerson.initializationStatus && selectedPerson.usageStatus) {
        statusExtraActions.push(
            <Popconfirm key={2} title={`确认要初始化吗?`} placement="topRight" okButtonProps={{ loading: initLoading }} onConfirm={updatePersonInit}>
                <Button type="primary" icon={<IconCopyAdd />}>
                    初始化
                </Button>
            </Popconfirm>
        );
    }

    if (selectedPerson.initializationStatus && !selectedPerson.usageStatus) {
        statusExtraActions.push(
            <Popconfirm key={3} title={`确认要取消初始化吗?`} placement="topRight" okButtonProps={{ loading: resetLoading }} onConfirm={updatePersonInit}>
                <Button type="primary" icon={<IconReply />}>
                    取消初始化
                </Button>
            </Popconfirm>
        );
    }

    if (!(selectedPerson.databaseUser && selectedPerson.databasePassword)) {
        extraActions.push(
            <Button
                key={1}
                loading={createUserLoading}
                icon={<IconUserAdd />}
                onClick={() =>
                    createDatabaseUser((res) => {
                        if (res) {
                            message.success("成功创建个人数据库用户信息");
                            reloadData();
                        }
                    })
                }
            >
                创建数据库用户
            </Button>
        );
    }

    if (selectedPerson.databaseUser && selectedPerson.databasePassword && !selectedPerson.databaseDbName) {
        extraActions.push(
            <Popconfirm
                key={2}
                title="确认要创建该个人的物理数据库吗?"
                okButtonProps={{ loading: createDBLoading }}
                placement="topRight"
                onConfirm={() =>
                    createDatabase((res) => {
                        if (res) {
                            message.success("成功创建个人物理数据库");
                            reloadData();
                        }
                    })
                }
            >
                <Button icon={<IconPlusCircle />}>创建数据库</Button>
            </Popconfirm>
        );
    }

    if (selectedPerson.databaseDbName) {
        extraActions.push(
            <Button key={3} icon={<IconDownload />} onClick={() => openUpdateDatabaseStructureModal(reloadData)}>
                更新数据库结构
            </Button>
        );
    }

    if (
        selectedPerson.databaseUser &&
        selectedPerson.databasePassword &&
        selectedPerson.databaseDbName &&
        selectedPerson.databaseSchemas?.length > 0 &&
        services.findIndex((item) => item.serviceName === "allinone_graphql_service") === -1
    ) {
        extraActions.push(
            <Popconfirm
                key={4}
                title="确认要创建数据服务吗?"
                placement="topRight"
                okButtonProps={{ loading: createDataServiceLoading }}
                onConfirm={() =>
                    createDataService((res) => {
                        if (res) {
                            message.success("成功创建个人数据服务");
                            loadAllServices();
                        }
                    })
                }
            >
                <Button icon={<IconPlusCircle />}>创建数据服务</Button>
            </Popconfirm>
        );
    }

    const cardExtra = <ButtonGroup>{extraActions}</ButtonGroup>;

    const serviceCardExtra = (
        <ButtonGroup>
            <Button icon={<IconRefresh />} onClick={loadAllServices}></Button>
        </ButtonGroup>
    );

    const renderServiceUseStatus = (_, record) => {
        let color = "#87d068";
        let text = "启用";
        let title = "确认要关闭该个人数据服务吗?";
        if (!record.serviceStatus) {
            color = "#f50";
            text = "未启用";
            title = "确认要开启该个人数据服务吗?";
        }
        return (
            <Popconfirm
                title={title}
                okButtonProps={{ loading: updateStatusLoading }}
                onConfirm={(e) => {
                    updateServiceStatus(record.serviceUuid, !record.serviceStatus, (res) => {
                        if (res) {
                            message.success("成功更改个人数据服务状态");
                            loadAllServices();
                        }
                    });
                }}
            >
                <Tag color={color}>{text}</Tag>
            </Popconfirm>
        );
    };

    const renderServiceRunStatus = (_, record) => {
        let color = "#87d068";
        let text = "运行中";
        let title = "确认要停止该个人数据服务吗?";
        if (!record.serviceRunning) {
            color = "#f50";
            text = "未运行";
            title = "确认要删除该个人数据服务吗?";
        }
        return (
            <span>
                <span style={{ color }}>{text}</span>(
                <Popconfirm
                    title={title}
                    okButtonProps={{ loading: record.serviceRunning ? stopLoading : deleteLoading }}
                    placement="topRight"
                    onConfirm={(e) =>
                        record.serviceRunning
                            ? stopService(record.serviceUuid, (res) => {
                                  if (res) {
                                      message.success("数据服务已停止运行");
                                      loadAllServices();
                                  }
                              })
                            : deleteService(record.serviceUuid, (res) => {
                                  if (res) {
                                      message.success("成功删除数据服务");
                                      loadAllServices();
                                  }
                              })
                    }
                >
                    <a>{record.serviceRunning ? "停止服务" : "删除服务"}</a>
                </Popconfirm>
                )
            </span>
        );
    };

    return (
        <div>
            <Card
                bordered={true}
                hoverable
                title="状态信息"
                style={{ marginBottom: 10 }}
                bodyStyle={{ padding: "10px 20px" }}
                extra={<ButtonGroup>{statusExtraActions}</ButtonGroup>}
            >
                <Descriptions column={3} labelStyle={{ width: 100 }}>
                    <Descriptions.Item label="核准状态">
                        {selectedPerson.verifyStatus ? <span className="green">已核准</span> : <span className="red">待核准</span>}
                    </Descriptions.Item>
                    <Descriptions.Item label="启用状态">
                        {selectedPerson.usageStatus ? <span className="green">已启用</span> : <span className="red">暂停使用</span>}
                    </Descriptions.Item>
                    <Descriptions.Item label="初始化状态">
                        {selectedPerson.initializationStatus ? <span className="green">已初始化</span> : <span className="red">未初始化</span>}
                    </Descriptions.Item>
                </Descriptions>
            </Card>

            <Card bordered={true} hoverable title="数据库信息" style={{ marginBottom: 10 }} bodyStyle={{ padding: 10 }} extra={cardExtra}>
                <Descriptions style={{ padding: "0 10px" }} column={3} labelStyle={{ width: 100 }}>
                    <Descriptions.Item label="用户名">{selectedPerson.databaseUser}</Descriptions.Item>
                    <Descriptions.Item label="用户密码">{selectedPerson.databasePassword}</Descriptions.Item>
                    <Descriptions.Item label="数据库版本">{selectedPerson.databaseVersionNo}</Descriptions.Item>
                </Descriptions>

                <Descriptions style={{ padding: "0 10px" }} column={3} labelStyle={{ width: 100 }}>
                    <Descriptions.Item label="数据库名" span={3}>
                        {selectedPerson.databaseDbName}
                    </Descriptions.Item>

                    <Descriptions.Item label="数据库模式" span={3}>
                        <Space wrap>
                            {selectedPerson.databaseSchemas?.map((item, i) => (
                                <Tag key={i}>{item}</Tag>
                            ))}
                        </Space>
                    </Descriptions.Item>
                </Descriptions>
            </Card>

            <Card bordered={true} hoverable title="服务信息" style={{ marginBottom: 16 }} bodyStyle={{ padding: 0 }} extra={serviceCardExtra}>
                <Table loading={loading} size="small" bordered={false} pagination={false} dataSource={services} rowKey={"serviceUuid"} style={{ marginTop: 1 }}>
                    <Table.Column title="序号" width={60} align="center" render={(_, r, i) => i + 1} />
                    <Table.Column title="服务名" dataIndex="serviceName" align="left" width={160} />
                    <Table.Column title="服务类型" dataIndex="serviceType" align="center" width={80} />
                    <Table.Column title="服务地址" align="left" render={(_, record) => record.serviceProtocol + record.serviceHost + ":" + record.servicePort} />
                    <Table.Column title="启用状态" align="center" width={80} render={renderServiceUseStatus} />
                    <Table.Column title="运行状态" align="center" width={140} render={renderServiceRunStatus} />
                </Table>
            </Card>
        </div>
    );
};

export default PersonDatabase;
